//公共方法js
import {downloadFile,saveFile} from "./wxapi";
import {compareVersion} from "./util";
import {POST} from "./netWork";
/**
 * 实物临期提醒只提示一次
 */
export const isShowReminderOfExpired=(id)=>{
    return new Promise((resolve,reject)=>{
        let list = wx.getStorageSync('reminderOfExpiredList') || [];
        let flag = true;
        for(let i of list){
            //当前实物的订单id已经在缓存中有,不在显示临期提醒授权
            if(i == id){
                flag = false;
                break;
            }
        }
        if(flag){
            resolve(flag);
        }else{
            resolve(flag);
        }
    })
}
/**
 * 播放缓存里的音频
 */
export const playAudio=()=>{
    if(getApp().videoPath == null || getApp().videoPath == ""){
        return; 
    }
    var res = wx.getSystemInfoSync()
    let audio = wx.createInnerAudioContext();
    if (compareVersion(res.SDKVersion, '2.3.0') >= 0) {//api在2.3.0以上可以使用
        wx.setInnerAudioOption({
            obeyMuteSwitch: false
        })
    }
　　audio.src = getApp().videoPath;
　　audio.play();
}
/**
 * 判断文件或目录是否存在
 */
export const fsAccess=(path)=>{
    return new Promise(async (resolve,reject)=>{
        const fs = wx.getFileSystemManager()
        // 判断文件/目录是否存在
        fs.access({
            path: path,
            success(res) {
                // 文件存在
                resolve(res);
            },
            fail(res) {
                // 文件不存在或其他错误
                resolve(res);
            }
        })
    })
}
/**
   * 授权手机号
   * @param {*} e
   */
  export const authUserPhone=(e)=>{
    // let encryptedData = "";
    // let iv = "";
    let code = "";
    // if(e.detail.encryptedData){
    //     encryptedData = e.detail.encryptedData;
    // }
    // if(e.detail.iv){
    //     iv = e.detail.iv;
    // }
    if(e.detail.code){
        code = e.detail.code;
    }
    console.log('authUserPhoneV3')
    return new Promise((resolve, reject) => {
      POST('authUserPhoneV3', {
        data: {
          userId: wx.getStorageSync('userId'),
        //   encryptedData: encodeURIComponent(encryptedData),
        //   iv: encodeURIComponent(iv),
          jsCode: wx.getStorageSync('code'),
          code:code
        },
        success: function (res) {
          if (res.data.retCode == undefined) {
            resolve(false);
          }
          if (res.data.retCode == '0000') {
              if(res.data.data.phone){
                wx.setStorageSync('userPhone', res.data.data.phone);
                resolve(true);
              }else{
                resolve(false);
              }
          } else {
            resolve(false);
          }
        },
        fail: function (res) {
          resolve(false);
        }
      });
    });
  }
  /**
   * 初始化消费者头像昵称
   */
  export const initCustomerAuthInfo=()=>{
    return new Promise((resolve, reject) => {
      POST('initCustomerAuthInfo', {
        data: {
          userId: wx.getStorageSync('userId')
        },
        success: function (res) {
            resolve(res);
        },
        fail: function (res) {
            resolve(res);
        }
      });
    });
  }
  /**
   * 获取世界杯竞猜信息接口
   */
  export const pickInfo=(prizeOrderId)=>{
    return new Promise((resolve, reject) => {
      POST('worldcup/pickInfo', {
        data: {
            prizeOrderId: prizeOrderId
        },
        success: function (res) {
            resolve(res);
        },
        fail: function (res) {
            resolve(res);
        }
      });
    });
  }
  /**
   * 修改世界杯竞猜奖励状态
   */
  export const setJingDianPrizeStatus=(that,e)=>{
    let prizeOrderId = e.detail.prizeOrderId;
    let index = 0;
    let prizeList = wx.getStorageSync('prizeList');
    for(let i=0;i<prizeList.length;i++){
        if(prizeList[i].prizeOrderId == prizeOrderId){
            index = i;
            break;
        }
    }
    let status = e.detail.status;
    prizeList[index].status = status;
    if(prizeList[index].worldcupInfo == null){
       prizeList[index].worldcupInfo = {
            status:0
        };
    }
    wx.setStorageSync('prizeList', prizeList)
    that.setData({
        prizeList,
        showFootball:false
    })
    that.setHandFlag();
  }
  /**
   * JS将阿拉伯数字转换为汉字
   */
  export const toChinese=(num)=>{
    return new Promise((resolve, reject) => {
        num=Math.floor(num);
        var chinese="";
        var digits=Math.floor(Math.log10(num))+1;
        var digit=['零','一','二','三','四','五','六','七','八','九'];
        var times=['','十','百','千','万'];
        if(digits>=9){
            var quotient=Math.floor(num/Math.pow(10,8));
            var remainder=num%Math.pow(10,8);
            var remainderDigits=Math.floor(Math.log10(remainder))+1;
            resolve(toChinese(quotient)+'亿'+(remainderDigits<8?"零":"")+(remainder>0?toChinese(remainder):""));
        }
        //10000 0000
        if(digits==1) {
            resolve(digit[num]);
        }
        if(digits==2){
            var quotient=Math.floor(num/10);
            var remainder=num%10;
            if(quotient>1){
                chinese=digit[quotient];
            }
            chinese=chinese+times[1];
            if(remainder>0){
                chinese=chinese+digit[remainder];
            }
            resolve(chinese);
        }
        if(digits>5){
            var quotient=num/Math.pow(10,4);
            var remainder=num%Math.pow(10,4);
            var remainderDigits=Math.floor(Math.log10(remainder))+1;
            resolve(toChinese(quotient)+'万'+(remainderDigits<4?"零":"")+(remainder>0?toChinese(remainder):""));
        }
        for(var index=digits;index>=1;index--) {
            var number=Math.floor(num/Math.pow(10,index-1)%10);
            if(number>0){
                chinese=chinese+digit[number]+times[index-1];
            }else{
                if(index>1) {
                    var nextNumber=Math.floor(num/Math.pow(10,index-2)%10);
                    if(nextNumber>0&&index>1){
                        chinese=chinese+digit[number];
                    }
                }            
            
            }

        }
        resolve(chinese);
    });
  }
  /**
   * 获取分支抽奖音频
   */
  export const getActivityMusicConfig=(productTypeId)=>{
    getApp().videoPath = null;
    POST('lotteryNew/getActivityMusicConfig', {
        data: {
            productTypeId,
            buttonType:1
        },
        success: async function (res) {
            // res.data.data.musicUrl = 'https://xhtx-touyun.oss-cn-shenzhen.aliyuncs.com/platform/pro/xhtxWechatAppImage/common/testMusic.mp3';
            if(res.data.data.musicUrl){
                let path = res.data.data.musicUrl;
                let audioList = wx.getStorageSync('audioList') || [];
                let cacheAudio = "";
                let index = -1;
                //找出有没有记录过当前路径的缓存音频
                for(let i of audioList){
                    if(i.originalAudio == path){
                        cacheAudio = i.cacheAudio;
                        index++;
                        break;
                    }
                }
                //判断缓存文件是否还存在手机里
                let isFs = "";
                if(cacheAudio != ""){
                    isFs = await fsAccess(cacheAudio);
                }
                let savedFilePath = "";
                if(isFs.errMsg == "access:ok"){ //存在用缓存的地址播放音频
                    savedFilePath = cacheAudio;
                }else{//不存在将网络音频转缓存后在播放，并记录小程序缓存中
                    //为了节省流量所以把拿到的音频存到缓存中在进行播放
                    let tempFilePath = await downloadFile(path);
                    if(tempFilePath == false){
                        return;
                    }
                    savedFilePath = await saveFile(tempFilePath);
                    if(index != -1){
                        audioList[index].cacheAudio = savedFilePath;
                    }else{
                        let obj = {};
                        obj.originalAudio = path;
                        obj.cacheAudio = savedFilePath;
                        audioList.push(obj);
                    }
                    wx.setStorageSync('audioList', audioList)
                }
                getApp().videoPath = savedFilePath;
            }
            
        },
        fail: function (res) {
            conosle.log('getActivityMusicConfig：'+res);
        }
    });
  }